package com.cygsunri.wisdompark.util.id;


import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * 主键ID工具类
 *
 * @author lhy
 * @date 2020/09/22
 **/

public class SnowFlakeIdWorker {

    private static IdGenerator idGenerator;
    private static SnWorker snWorker = new SnWorker(1, 1);

    static {
        Properties props = System.getProperties();
        String workerId = props.getProperty("WORKER_ID");
        if (workerId != null && isNumeric(workerId)) {
            idGenerator = new SnowflakeIdGenerator(Long.parseLong(workerId));
        } else {
            idGenerator = new SnowflakeIdGenerator(1);
        }
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    /**
     * 获取主键
     *
     * @return long
     */
    public static synchronized long generateNextId() {
        return idGenerator.nextId();
    }

    /**
     * 获取主键
     *
     * @return String
     */
    public static synchronized String generateNextIdStr() {
        return String.valueOf(idGenerator.nextId());
    }


    public static synchronized String getSn() {
        Long thisTime = Long.parseLong(new SimpleDateFormat("yyyyMMdd")
                .format(new Date()));
        BigInteger bigInteger = new BigInteger(thisTime.toString());
        bigInteger = bigInteger.multiply(
                BigInteger.valueOf((long) Math.pow(10, 12))).add(
                BigInteger.valueOf((snWorker.nextId() % 1000000000000L)));
        return bigInteger.toString();
    }

}